<?php

namespace App\Http\Controllers\Mobile;

use App\Interfaces\PictureService;
use App\Models\Picture;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\OSS;

class FileUploadController extends Controller
{
    public function index(){
        return view('admin.file_upload.index');
    }
    public function store(Request $request,PictureService $pictureService){
        //dd($request->all());
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $filePath = $file->getRealPath();
            $fileExt = $file->getClientOriginalExtension();
            $fileMimeType = $file->getMimeType();
            $fileSize = $file->getClientSize();
            $fileName = $file->getClientOriginalName();

            //同步到OSS
            $id = md5(uniqid(mt_rand(), true));
            $newFileName = $id.'.'.$fileExt;
            $return = OSS::upload($newFileName, $filePath); // 上传一个文件

            if ($return){
                //插入数据库

                Picture::create([
                    'id'=>$id,
                    'file_path'=>$newFileName,
                    'file_name'=>$fileName,
                    'file_size'=>$filePath,
                    'file_ext'=>$fileExt,
                    'file_mime_type'=>$fileMimeType
                ]);
            }
        }

        $json = [
            'success'=>true,
            'name'=>$fileName,
            'id'=>$id,
            'url'=>$pictureService::thumb($id),
            'file_path'=>$pictureService::thumb($id)
        ];
        return Response()->json($json);
    }

}
